package yunjiao.javatutorials.guava.concurrent;

import com.google.common.util.concurrent.SettableFuture;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 线程池配合使用
 *
 * SettableFuture 可作为 "结果载体"，与 JDK 线程池结合，实现更灵活的异步流程
 *
 * @author yangyunjiao
 */
public class SettableFutureThreadPoolDemo {
    public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newFixedThreadPool(2);
        SettableFuture<String> future = SettableFuture.create();

        // 线程1：处理业务并设置结果
        executor.submit(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            future.set("线程池处理结果");
        });

        // 线程2：监听结果并处理
        executor.submit(() -> {
            try {
                String result = future.get();
                System.out.println("线程2处理结果：" + result);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        // 主线程等待结果
        System.out.println("主线程获取结果：" + future.get());
        executor.shutdown();
    }
}
